package com.jacen.etl.util;

public class DBFeature
{
  public static IDBFeature feature = new OracleFeature();

  public static void changeDB(DBFeature.DBServer server) {
    switch (server.ordinal()) {
    case 0:
      break;
    case 1:
      feature = new MysqlFeature();
      break;
    case 2:
      feature = new DB2Feature();
      break;
    }
  }

  public static enum DBServer
  {
    Oracle, 
    Mysql, 
    DB2;
  }

  static class DB2Feature
    implements DBFeature.IDBFeature
  {
    public String toDate()
    {
      return " TIMESTAMP(?) ";
    }

    public String pageSql(String orginSql, int start, int end)
    {
      StringBuilder sb = new StringBuilder();
      sb.append(" select * from  ");
      sb.append(" (  ");
      sb.append(" \tselect ROW_NUMBER() AS ROWNUM, b.* from ( %s ) b ");
      sb.append(" ) a ");
      sb.append(" where ROWNUM > %d and ROWNUM <=%d ");
      return String.format(sb.toString(), new Object[] { orginSql, Integer.valueOf(start), Integer.valueOf(end) });
    }
  }

  static class MysqlFeature
    implements DBFeature.IDBFeature
  {
    public String toDate()
    {
      return " ? ";
    }

    public String pageSql(String orginSql, int start, int end)
    {
      String sql = "%s limit %d, %d";
      return String.format(sql, new Object[] { orginSql, Integer.valueOf(start), Integer.valueOf(end - start) });
    }
  }

  static class OracleFeature
    implements DBFeature.IDBFeature
  {
    public String toDate()
    {
      return " to_date(?, 'yyyy-mm-dd hh24:mi:ss') ";
    }

    public String pageSql(String orginSql, int start, int end)
    {
      StringBuilder sb = new StringBuilder();
      sb.append("select AA.* from ");
      sb.append("( ");
      sb.append("  select rownum as rn, TT.* ");
      sb.append("  from (%s) TT");
      sb.append(") AA ");
      sb.append("where rn > %d and rn <= %d ");
      return String.format(sb.toString(), new Object[] { orginSql, Integer.valueOf(start), Integer.valueOf(end) });
    }
  }

  public static abstract interface IDBFeature
  {
    public abstract String toDate();

    public abstract String pageSql(String paramString, int paramInt1, int paramInt2);
  }
  
  public static void main(String[] args) {
	  DBFeature.changeDB(DBServer.Mysql);
  }
}
